/*******************************************************************************
 * Licensed Materials - Property of IBM
 * (c) Copyright IBM Corporation 2005, 2008. All Rights Reserved. 
 * 
 * Note to U.S. Government Users Restricted Rights:  Use, 
 * duplication or disclosure restricted by GSA ADP Schedule 
 * Contract with IBM Corp.
 *******************************************************************************/

package org.eclipsecon.dui.interpreter.internal;

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.ui.progress.UIJob;
import org.eclipsecon.dui.databinding.DModel;

import java.util.Collections;

public class BindingJob extends UIJob {
	private final String fBinding;
	private final String fModel;
	private final ModelContainer fModelContainer;
	private final ModelContext context;

	public BindingJob(ModelContainer modelContainer, ModelContext context, String binding, String model) {
		super("Bind");
		fModelContainer= modelContainer;
		this.context = context;
		fBinding= binding;
		fModel= model;
	}

	/*
	 * @see org.eclipse.ui.progress.UIJob#runInUIThread(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public IStatus runInUIThread(IProgressMonitor monitor) {
		DataBindingContext bindingContext= new EMFDataBindingContext();
		Resource bindingRes= fModelContainer.getResourceSet().createResource(URI.createFileURI(fBinding));
		Resource modelRes= fModelContainer.getResourceSet().createResource(URI.createFileURI(fModel));
		try {
			bindingRes.load(Collections.EMPTY_MAP);
			modelRes.load(Collections.EMPTY_MAP);
			DModel model= (DModel) bindingRes.getContents().get(0);
			EObject rootModelElement = modelRes.getContents().get(0);
			context.setModel(rootModelElement);
			context.setBindingJob(this);
			BindingSwitch bs= new BindingSwitch(bindingContext, rootModelElement);
			bs.doSwitch(model);
			
			fModelContainer.setBindingPath(fBinding);
			fModelContainer.setDataPath(fModel);
		} catch (Exception e) {
			return Activator.createStatus(e);
		}
		return Status.OK_STATUS;
	}
}